package com.xmkj.bearuser.membercenter;

import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.common.base.Config;
import com.common.cons.Constans;
import com.common.mvp.BaseMvpFragment;
import com.common.mvp.BasePresenter;
import com.common.retrofit.bean.MyShareBean;
import com.common.retrofit.bean.UserBean;
import com.common.retrofit.bearusermethod.GetShareDataMineMethods;
import com.common.retrofit.bearusermethod.GetUserInrfoMethods;
import com.common.retrofit.method.ShareSuccessMethods;
import com.common.retrofit.subscriber.CommonSubscriber;
import com.common.retrofit.subscriber.SubscriberListener;
import com.common.rxbus.RxBus;
import com.common.rxbus.postevent.RxKeyEvent;
import com.common.utils.EmptyUtils;
import com.common.utils.SPUtils;
import com.common.widget.imageview.image.ImageLoaderUtils;
import com.common.widget.itemview.BaseItemLayout;
import com.common.widget.itemview.config.ConfigAttrs;
import com.common.widget.itemview.config.Mode;
import com.xmkj.bearuser.R;
import com.xmkj.bearuser.count.LoginActivtiy;
import com.xmkj.bearuser.mine.activity.InfoCompileActivity;
import com.xmkj.payandlogin.ShareConfig;
import com.xmkj.payandlogin.ShareManager;
import com.xmkj.payandlogin.ShareUtil;
import com.xmkj.payandlogin.share.ShareListener;
import com.xmkj.payandlogin.share.SharePlatform;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.functions.Action1;

/**
 * Create by leo
 * 创建日期：2018/7/13
 * 描述：
 */

public class MemberCenterFragment extends BaseMvpFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.iv_img)
    ImageView ivImg;
    @BindView(R.id.tv_jifen)
    TextView tvJifen;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.layout_mine)
    BaseItemLayout layoutMine;
    @BindView(R.id.swip_refreshs)
    SwipeRefreshLayout swipRefreshs;
    Unbinder unbinder;
    private ConfigAttrs attrs;
    private UserBean userBean;

    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_member_center;
    }

    @Override
    protected void onViewCreated(View view) {

    }

    @Override
    protected void doLogicFunc() {
        ShareConfig config = ShareConfig.instance()
                .qqId(Config.APP_QQ_ID)
                .wxSecret(Config.APP_SERECET)
                .wxId(Config.APP_ID);
        ShareManager.init(config);
        setMineItemView();
        swipRefreshs.setOnRefreshListener(this);
        attachClickListener(ivImg);
        attachClickListener(tvName);

        if (EmptyUtils.isNotEmpty(SPUtils.getShareString(Constans.HASHID))) {
            getUserInfo();
        }else {
            ivImg.setBackground(getResources().getDrawable(R.mipmap.oval_logo));
        }
        rxManager.add(RxBus.getDefault().toObservable(RxKeyEvent.class).subscribe(new Action1<RxKeyEvent>() {
            @Override
            public void call(RxKeyEvent rxKeyEvent) {
                if (EmptyUtils.isNotEventEmpty(rxKeyEvent, RxKeyEvent.MODIFYSUCCESS) && (Boolean) rxKeyEvent.getValue()) {
                    getUserInfo();
                }
            }
        }));
    }

    @Override
    protected void onViewClicked(View view) {
        if(EmptyUtils.isEmpty(SPUtils.getShareString(Constans.HASHID))){
            gotoActivity(LoginActivtiy.class);
            return;
        }
        if (view.getId() == tvName.getId() || view.getId() == ivImg.getId()) {
            gotoActivity(InfoCompileActivity.class);

        }
    }

    @Override
    public void bindKnife() {
        unbinder = ButterKnife.bind(this, view);
    }

    private void setMineItemView() {
        if (EmptyUtils.isNotEmpty(layoutMine) && layoutMine.getChildCount() > 0) {
            layoutMine.removeAllViews();
            layoutMine.getViewList().clear();
        }
        List<String> valueList = new ArrayList<>();
        List<Integer> resIdList = new ArrayList<>();
        valueList.add("储值明细");
        valueList.add("积分明细");
        valueList.add("分享奖励");
        valueList.add("个人资料");
        valueList.add("分享好友");
        valueList.add("我的收藏");

        resIdList.add(R.mipmap.chuzhidetail);
        resIdList.add(R.mipmap.jifendetails);
        resIdList.add(R.mipmap.share_reward);
        resIdList.add(R.mipmap.person_info);
        resIdList.add(R.mipmap.share_friend);
        resIdList.add(R.mipmap.my_collections);
        resIdList.add(R.mipmap.kefu);
        attrs = new ConfigAttrs();
        attrs.setValueList(valueList)  // 文字 list
                .setResIdList(resIdList) // icon list
                .setIconWidth(25)  //设置icon 的大小
                .setIconHeight(25)
                .setItemMode(Mode.TEXT)
                .setItemMarginTop(1)
                .setArrowResId(R.mipmap.next)
                .setMarginRight(12);
        layoutMine.setConfigAttrs(attrs).create();
        layoutMine.setOnBaseItemClick(new BaseItemLayout.OnBaseItemClick() {
            @Override
            public void onItemClick(int position) {
                if (EmptyUtils.isEmpty(SPUtils.getShareString(Constans.HASHID))) {
                    gotoActivity(LoginActivtiy.class);
                    return;
                }
                switch (position) {
                    case 0:/*  // 中奖记录
                        Intent intent = new Intent(context,MyWalletActivity.class);
                        intent.putExtra(Constans.INFOBEAN,infoBean);
                        startActivity(intent);*/
                        gotoActivity(ChuZhiDetailsActivity.class);

                        break;
                    case 1:
                        gotoActivity(JifenDetailsActivity.class);

//                        return;                gotoActivity(JifenDetailsActivity.class);
//                        gotoActivity(ApplyForBillActivity.class);
                        break;
                    case 2:
//                        gotoActivity(WashCarRecordActivity.class);
                        // 我的晒单
//                        gotoActivity(MyShareOrderActivity.class);
                        gotoActivity(SharRewardActivity.class);
//                        Intent intent2 = new Intent(context, BaseUrlActivity.class);
//                        intent2.putExtra(BaseUrlActivity.MAIN_URL, mineBean.kefu);
//                        intent2.putExtra(BaseUrlActivity.TITILE, "服务中心");
//                        context.startActivity(intent2);
////
//                        Intent surlIntent = new Intent(context, BaseUrlActivity.class);
//                        surlIntent.putExtra(BaseUrlActivity.MAIN_URL,mineBean.kefu);
//                        startActivity(surlIntent);
                        break;
                    case 3:
                        gotoActivity(InfoCompileActivity.class);
//                        gotoActivity(MyCardActivity.class);

//                        Intent intent3 = new Intent(context, BaseUrlActivity.class);
//                        intent3.putExtra(BaseUrlActivity.MAIN_URL, mineBean.cjwt);
//                        intent3.putExtra(BaseUrlActivity.TITILE, "常见问题");
//                        context.startActivity(intent3);
                        break;
                    case 4:

                        //收货地址
//                        gotoActivity(FaPiaoApplyActivity.class);
                        getShareDate();

                        break;
                    case 5:
                        //信用额度
//                        gotoActivity(CriditLimitActivity.class);
//                        gotoActivity(SettingActivity.class);
//                        getShareData();
                        gotoActivity(MyCollectionActivity.class);
                        break;


                }
            }
        });
    }

    private void getShareDate() {
        CommonSubscriber<MyShareBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {

                dismissProgressDialog();
                MyShareBean  myShareBean = (MyShareBean) o;
                if(EmptyUtils.isNotEmpty(myShareBean)){
                    gotoShare(myShareBean);
                }


            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                swipRefreshs.setRefreshing(false);
                showToastMsg(e);
            }
        });
        uid = SPUtils.getShareInt(Constans.UID);
        hashid = SPUtils.getShareString(Constans.HASHID);
        GetShareDataMineMethods.getInstance().share(subscriber, uid, hashid);
        rxManager.add(subscriber);
    }

    private void gotoShare(final MyShareBean shareEntity) {
        showShareButton();
        setOnShareClick(new OnShareClick() {
            @Override
            public void wechat() {
                if (ShareUtil.isInstalled(SharePlatform.WX, context)) {

//                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon);
//                    if (EmptyUtils.isEmpty(mineBean.img)) {
//                        ShareUtil.shareMedia(context, SharePlatform.WX, mineBean.title, mineBean.content, mineBean.url, bitmap, shareListener);
//
//                    } else {
//                        ShareUtil.shareMedia(context, SharePlatform.WX, mineBean.title, mineBean.content, mineBean.url, mineBean.img, shareListener);
                    ShareUtil.shareMedia(context, SharePlatform.WX, shareEntity.share.title.equals("") ? "贝儿凯丽" : shareEntity.share.title, shareEntity.share.content, shareEntity.share.share_url, shareEntity.share.pic_url, shareListener);
//                    }
//                    ShareUtil.shareImage(context, SharePlatform.WX, shareEntity.qr_code,shareListener);

                } else {
                    showToastMsg("未安装微信");
                }
            }

            @Override
            public void wethatCircle() {
                if (ShareUtil.isInstalled(SharePlatform.WX_TIMELINE, context)) {
//                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon);
//                    if (EmptyUtils.isEmpty(mineBean.img)) {
                    ShareUtil.shareMedia(context, SharePlatform.WX_TIMELINE, shareEntity.share.title.equals("") ? "贝尔凯丽" : shareEntity.share.title, shareEntity.share.content, shareEntity.share.share_url, shareEntity.share.pic_url, shareListener);
//
//                    } else {
//                        ShareUtil.shareMedia(context, SharePlatform.WX_TIMELINE, mineBean.title, mineBean.content, mineBean.url, mineBean.img, shareListener);
//                    ShareUtil.shareMedia(context, SharePlatform.WX_TIMELINE, shareEntity.share_title.equals("") ? "拼夺宝" : shareEntity.share_title, shareEntity.share_content, shareEntity.share_url, shareEntity.logo, shareListener);
//                    }
                } else {
                    showToastMsg("未安装微信");
                }
            }

            @Override
            public void qq() {
                if (ShareUtil.isInstalled(SharePlatform.QQ, context)) {
//                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon);
               /*     if (EmptyUtils.isEmpty(mineBean.img)) {
                        ShareUtil.shareMedia(context, SharePlatform.QQ, mineBean.title, mineBean.content, mineBean.url, bitmap, shareListener);

                    } else {*/
//                        ShareUtil.shareMedia(context, SharePlatform.QQ, mineBean.title, mineBean.content, mineBean.url, mineBean.img, shareListener);
//                    ShareUtil.shareMedia(context, SharePlatform.QQ, shareEntity.share_title.equals("") ? "拼夺宝" : shareEntity.share_title, shareEntity.share_content, shareEntity.share_url, shareEntity.logo, shareListener);
//                    }

                } else {
                    showToastMsg("未安装QQ");
                }
            }
        });
    }
    private ShareListener shareListener = new ShareListener() {
        @Override
        public void shareSuccess() {
            showToastMsg("分享成功");
            Sharesuccessfully();
        }

        @Override
        public void shareFailure(Exception e) {
            showToastMsg("分享失败");
        }

        @Override
        public void shareCancel() {
            showToastMsg("取消分享");
        }
    };
    private void Sharesuccessfully() {
        CommonSubscriber<Object> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();

                //                gotoHttpRep();
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });
        ShareSuccessMethods.getInstance().shareSuccess(subscriber, SPUtils.getShareInt(Constans.UID),SPUtils.getShareString(Constans.HASHID));
        rxManager.add(subscriber);
    }
    @Override
    public void onRefresh() {
        getUserInfo();
    }

    private void getUserInfo() {
        CommonSubscriber<UserBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                swipRefreshs.setRefreshing(false);
                dismissProgressDialog();
                userBean = (UserBean) o;
                tvName.setText(userBean.username);
                tvMoney.setText(userBean.account);
                tvJifen.setText(userBean.score);
                if (EmptyUtils.isNotEmpty(userBean.face)) {
                    ImageLoaderUtils.displayCircle(ivImg, userBean.face);
                }


            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                ivImg.setBackground(getResources().getDrawable(R.mipmap.oval_logo));
                tvName.setText(" ");
                swipRefreshs.setRefreshing(false);
//                showToastMsg(e);
            }
        });
        uid = SPUtils.getShareInt(Constans.UID);
        hashid = SPUtils.getShareString(Constans.HASHID);
        GetUserInrfoMethods.getInstance().UserInfo(subscriber, uid, hashid);
        rxManager.add(subscriber);
    }
}
